package com.example.accessingdatajpa.service.impl;

import com.example.accessingdatajpa.exception.ResourceNotFoundException;
import com.example.accessingdatajpa.picrepository.FirstPagePicRepository;
import com.example.accessingdatajpa.pojo.FirstPagePicture;
import com.example.accessingdatajpa.service.IFirstPagePicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

@Service("firstPagePicService")
public class FirstPagePicService implements IFirstPagePicService {
    @Autowired
    private FirstPagePicRepository firstPagePicRepository;
    //insert a picture of first page
    @Override
    @Transactional
    public void insertFirstPagePic(FirstPagePicture firstPagePicture, MultipartFile file) throws IOException {
        FirstPagePicture firstPagePicture1 = new FirstPagePicture();
        if(file==null)
        {
            firstPagePicture1.setFirstPageImg(null);
        }else {
            firstPagePicture1.setFirstPageImg(file.getBytes());
        }
        firstPagePicRepository.save(firstPagePicture1);
    }



    //find the first-page's picture by id
    @Override
    @Transactional
    public void queryFirstPagePicById(Long id, HttpServletResponse response) throws IOException {
        FirstPagePicture firstPagePicture = firstPagePicRepository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("Fruit","id",id));
        byte[] data = firstPagePicture.getFirstPageImg();
        response.setContentType("image/png");
        response.setCharacterEncoding("UTF-8");
        OutputStream outputStream = response.getOutputStream();
        InputStream inputStream = new ByteArrayInputStream(data);
        int len = 0;
        byte[] buf = new byte[1024];
        while ((len = inputStream.read(buf,0,1024))!=-1){
            outputStream.write(buf,0,len);
        }
        inputStream.close();
        outputStream.close();
    }

    //update the first-page's picture by id
    @Override
    @Transactional
    public void updateFirstPagePicById(Long id, MultipartFile file) throws IOException {
        FirstPagePicture firstPagePicture = firstPagePicRepository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("Fruit","id",id));
        firstPagePicture.setFirstPageImg(file.getBytes());
    }
}
